"""
指标实时采样模块
"""
from typing import Callable, Optional, List
import time
import random
from PySide6.QtCore import QThread, Signal, QTimer
try:
    from .data_model import TraceEvent, MetricsModel
    from .config import CONFIG
except ImportError:
    from data_model import TraceEvent, MetricsModel
    from config import CONFIG


class MetricsSampler(QThread):
    """指标采样器（后台线程）"""
    
    # 信号定义
    event_sampled = Signal(TraceEvent)  # 单个事件采样
    batch_sampled = Signal(list)  # 批量事件采样
    sampling_error = Signal(str)  # 采样错误
    
    def __init__(self, parent: Optional[object] = None):
        super().__init__(parent)
        self._running = False
        self._sample_rate = CONFIG.sampling.sample_rate
        self._batch_size = CONFIG.sampling.batch_size
        self._custom_sampler: Optional[Callable] = None
    
    def set_sample_rate(self, rate: int) -> None:
        """设置采样频率"""
        self._sample_rate = rate
    
    def set_custom_sampler(self, sampler: Callable[[], TraceEvent]) -> None:
        """设置自定义采样函数"""
        self._custom_sampler = sampler
    
    def run(self) -> None:
        """采样主循环"""
        self._running = True
        batch: List[TraceEvent] = []
        interval = 1.0 / self._sample_rate  # 采样间隔
        
        while self._running:
            try:
                # 采样单个事件
                event = self._sample_event()
                
                # 发送单个事件信号
                self.event_sampled.emit(event)
                
                # 批量收集
                batch.append(event)
                if len(batch) >= self._batch_size:
                    self.batch_sampled.emit(batch.copy())
                    batch.clear()
                
                # 控制采样频率
                time.sleep(interval)
                
            except Exception as e:
                self.sampling_error.emit(str(e))
        
        # 发送剩余批次
        if batch:
            self.batch_sampled.emit(batch)
    
    def _sample_event(self) -> TraceEvent:
        """采样单个事件"""
        if self._custom_sampler:
            return self._custom_sampler()
        
        # 默认模拟采样
        return self._simulate_event()
    
    def _simulate_event(self) -> TraceEvent:
        """模拟生成事件（用于测试）"""
        event_types = ['CPU', 'GPU', 'Memory', 'IO', 'Network', 'Disk']
        return TraceEvent(
            timestamp=time.time() * 1000000,  # 微秒
            event_type=random.choice(event_types),
            thread_id=random.randint(1, 16),
            process_id=random.randint(1000, 9999),
            duration=random.uniform(1.0, 1000.0),
            metadata={'source': 'simulator'}
        )
    
    def stop(self) -> None:
        """停止采样"""
        self._running = False
        self.wait()


class RealTimeSamplingController:
    """实时采样控制器"""
    
    def __init__(self, model: MetricsModel):
        self.model = model
        self.sampler = MetricsSampler()
        
        # 连接信号
        self.sampler.batch_sampled.connect(self._on_batch_sampled)
        self.sampler.sampling_error.connect(self._on_error)
    
    def start(self) -> None:
        """启动采样"""
        self.sampler.start()
    
    def stop(self) -> None:
        """停止采样"""
        self.sampler.stop()
    
    def _on_batch_sampled(self, events: List[TraceEvent]) -> None:
        """处理批量采样事件"""
        self.model.add_events_batch(events)
    
    def _on_error(self, error_msg: str) -> None:
        """处理错误"""
        print(f"Sampling error: {error_msg}")
